﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http.Filters;
using Treasure.Service;
using Treasure.Service.DBModel;
using Treasure.Service.Utility;

namespace Trasure.Service.Filters
{
    public class SecurityFilter: ActionFilterAttribute
    {
        private Logger logger = new Logger(typeof(SecurityFilter));
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            //Login方法不需要进行签名验证
            if (actionContext.ActionDescriptor.ActionName == "Login")
            {
                base.OnActionExecuting(actionContext);
                return;
            }

            HttpResponseMessage result = null;
            var request = actionContext.Request;
            string token = string.Empty;
            string userid = string.Empty;
            if (request.Headers.Contains("userid"))
            {
                userid = HttpUtility.UrlDecode(request.Headers.GetValues("userid").FirstOrDefault());
            }
            if (request.Headers.Contains("token"))
            {
               token = HttpUtility.UrlDecode(request.Headers.GetValues("token").FirstOrDefault());
            }
            logger.Info($"token信息:request-userid={userid};request-token={token}");
            //判断token是否有效
            if (string.IsNullOrEmpty(token) || CacheHelps.Get<User>(token) == null || CacheHelps.Get<User>(token).id.ToString() != userid)
            {
                logger.Info($"token失效");
                actionContext.Response = new HttpResponseMessage((HttpStatusCode)401);
                base.OnActionExecuting(actionContext);
                return;
            }
            else
            {
                logger.Info($"token验证通过");               
                base.OnActionExecuting(actionContext);

            }
        }
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);
        }
    }
}